<?php
/**
 * Author  : DAMMAK Wassim
 * Contact : wdammak@talend.com
 * Date    : 12/2008
 * @copyright talend.com 2008
 * @license GNU/GPL Version 2
 **/  
 
//if(empty($_SESSION)) die('no permissions for access');			 
	 
function php2js( $php_array, $js_array_name ) {
	// contrle des parametres d'entre
	if( !is_array( $php_array ) ) {
		//trigger_error( "php2js() => 'array' attendu en parametre 1, \n'".gettype($array)."' fourni !?!");
		return false;
	}
	if( !is_string( $js_array_name ) ) {
		//trigger_error( "php2js() => 'string' attendu en parametre 2, \n'".gettype($array)."' fourni !?!");
		return false;
	}

	// Cration du tableau en JS
	$script_js = "var $js_array_name = new Array();\n";
	
	// on rempli le tableau JS  partir des valeurs de son homologue PHP
	foreach( $php_array as $key => $value ) {
		if(!is_array($value)){		
			$value=str_replace("\r\n","",$value);
			$value=str_replace("\n\r","",$value);
			$value=str_replace("\n","",$value);
			$value=str_replace("\r","",$value);			
			$value=str_replace("","\\n",$value);
			$value=str_replace('&#x',"%u",$value);
			//$value=str_replace('%u',"%u",$value);
		}
		// pouf, on tombe sur une dimension supplementaire
		if( is_array($value) ) {
			// On va demander la cration d'un tableau JS temporaire
			$temp = uniqid('temp_'); // on lui choisi un nom bien barbare
			$t = php2js( $value, $temp ); // et on creer le script JS
			// En cas d'erreur, remonter l'info aux rcursions suprieures
			if( $t===false ) return false;

			// Ajout du script de cration du tableau JS temporaire
			$script_js.= $t;
			// puis on applique ce tableau temporaire  celui en cours de construction
			$script_js.= "{$js_array_name}['{$key}'] = {$temp};\n";
		}
		
		// Si la clef est un entier, pas de guillemets
		elseif( is_int($key) )  $script_js.= "{$js_array_name}[{$key}] = '{$value}';\n";
		
		// sinon avec les guillemets
		else 
			$script_js.= "{$js_array_name}['{$key}'] = '{$value}';\n";
	}

	// Et retourn le script JS
	return $script_js;
}

function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

} 

function mySerialize($array, $key){
	$string="";
	if(count($array)>0){
		foreach($array as $itm)
			$string.=$itm[$key].",";
			
		if(substr($string,-1)==",")
			$string=substr($string,0,-1);
	}
	return $string;
}

/**
 * Sorts an array according to a specified column
 * Params : array  $table
 *          string $colname
 *          bool   $numeric
 **/
function sort_col($table, $colname, $order=SORT_ASC) {
  $tn = $ts = $temp_num = $temp_str = array();
  foreach ($table as $key => $row) {
  	$row =array_flatten_recursive($row);
    if(is_numeric(substr($row[$colname], 0, 1))) {
      $tn[$key] = $row[$colname];
      $temp_num[$key] = $row;
	  $temp_num[$key]['key']=$key;
    }
    else {
      $ts[$key] = $row[$colname];
      $temp_str[$key] = $row;
	  $temp_str[$key]['key']=$key;
    }
  }
  unset($table);

  array_multisort($tn, $order, SORT_NUMERIC, $temp_num);
  array_multisort($ts, $order, SORT_STRING, $temp_str);
  
  return array_merge($temp_num, $temp_str);
}

function array_flatten_recursive($array,$std=true) {
	if($array) {
		$flat = array();
		foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST) as $key=>$value) {
			if(!is_array($value)) {
				if($std==true){
					$flat[$key] = $value;
				}else{
					$flat[] = $value;
				}
			}
		}
 
		return $flat;
	} else {
		return false;
	}
}

//OutPut Sentences
function echoSentences($arr){
	global $arrLanguesShortName;
	$str_sent='';
	if(count($arr)>0)
		foreach($arr as $translated)
			if($translated['nbr']>0)
				$str_sent.='<option class="'.$arrLanguesShortName[$translated['language_id']].'">'.$translated['nbr']."</option>";				
	return $str_sent;
}

//Get langue browser
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !isset($_SESSION['babili']['ln_browser']) ){
	$Langue_str = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
	$Langue_brw = strtolower(substr(chop($Langue_str[0]),0,2));
	//$full_Langue_name=strtolower(substr(chop($Langue_str[0]),0,5));
}

if(!isset($_SESSION['babili']['groupe'])){
	$first=true;
}

//Get Groupe
if(!isset($_SESSION['babili']['gid'])){
	
	$groupe="guest";

	if($myAdapter->isActive()) {
	
		switch($myAdapter->getGid()) {
			case 1: 
				$groupe="editor";
				break;
			case 2: 
				$groupe="staff";
				break;
			case 3: 
				$groupe="admin";
				break;
			default :
				$groupe="guest";
				break;
		}
		
	}else{
		echo "<style class='noactived'>Your account is not activated!</span><br />";
	}
	
	$_SESSION['babili']['groupe']=$groupe;
	$_SESSION['babili']['gid']= $myAdapter->getGid();		
}

/** Instance ACL **/
$acl = new Acl($myAdapter);

/** 
 * Interroger les ACL 
 * Examples : 
 **
	echo $acl->isAllowed(null, 'voir') ? "autorise<br/>" : "refuse<br/>"; // autorise
	
	echo $acl->isAllowed(null, 'publier') ? "autorise<br/>" : "refuse<br/>"; // refuse
	
	echo $acl->isAllowed(null, 'relire') ? "autorise<br/>" : "refuse<br/>"; // autorise
	
	echo $acl->isAllowed(null, 'voir') ? "autorise<br/>" : "refuse<br/>"; // autorise parce que herite de Invite
	
	echo $acl->isAllowed(null, 'modifier') ? "autorise<br/>" : "refuse<br/>"; // refuse parce qu'il n'y a pas de regle pour 'modifier'
	
	echo $acl->isAllowed(null, 'voir') ? "autorise<br/>" : "refuse<br/>"; // autorise car administrateur est autorise pour tout
	
	echo $acl->isAllowed($groupe) ? "autorise<br/>" : "refuse<br/>"; // autorise car administrateur est autorise pour tout
	
	echo $acl->isAllowed(null, 'modifier') ?  "autorise<br/>" : "refuse<br/>"; // autorise car administrateur est autorise pour tout

*/
		 

/*************************************************
//Set Ajax email User
*************************************************/
echo "<script> var my_email='".$myAdapter ->getIdentity ()."';</script>";

/*************************************************
//Get Id User
*************************************************/
$resultUser = $myAdapter->getId();
if(!isset($_SESSION['babili']['id_user'])){
	$_SESSION['babili']['id_user'] = new stdClass; 
}
$_SESSION['babili']['id_user']=$resultUser;


/*************************************************
//Get User translated word
*************************************************/

 //Query Translated	
 $query = "
	SELECT `language_id`, count(`property_key_id`) as nbr 
	FROM `translation`
	WHERE `contributor_id`='".$_SESSION['babili']['id_user']->id_user."' 
	GROUP BY `language_id`
 ";
 
 $resultTranslated = fetchArray($query);

 //Query Validated
 $query = "
	SELECT `language_id`, count(`property_key_id`) as nbr 
	FROM `translation`
	WHERE `validator_id`='".$_SESSION['babili']['id_user']->id_user."' 
	GROUP BY `language_id`
 ";
 $resultValidated = fetchArray($query);

//Make list of Short_name languages
$arrLanguesShortName=array();

$classesFlags='<style type="text/css">';

foreach($resultLangues as $langue){
	$arrLanguesShortName[$langue['id']]=$langue['country_code'];
	$classesFlags.= ".".$langue['country_code']."{background:url(".$langue['flag'].") no-repeat right; padding-right:16px;}";
}

$classesFlags.='</style>';	

/*************************************************
//Get Selected Langue
*************************************************/	
	$nbrDefaultSelectLangue=1;
	if(isset($_SESSION['babili']['refLang'])){
		$first=false; 
	}else{
		$first=true;
	}
	
	$i=0;
	foreach($resultLangues as $langue){
		if($first==true){ //First execution
			$_SESSION['babili']['language'][$langue['country_code']] = new stdClass; 
			$_SESSION['babili']['language'][$langue['country_code']]->language = $langue;
			
			if($i<$nbrDefaultSelectLangue){
				$_SESSION['babili']['language'][$langue['country_code']]->isSelect = true;
			}else{
				$_SESSION['babili']['language'][$langue['country_code']]->isSelect = false;
			}
			
		}
		$i++;
		
		if(isset($_POST['lang'])){
			foreach($resultLangues as $langue){
				$is_sel=false;
				if(is_array($_POST['lang'])){
					foreach($_POST['lang'] as $post_lang){
						if($post_lang==$langue['country_code']){
							$_SESSION['babili']['language'][$langue['country_code']]->isSelect=true;
							$is_sel=true;
							break;
						}
					}
				}else{
					$is_sel=true;
					$_SESSION['babili']['language'][$langue['country_code']]->isSelect=true;
					break;
				}
				
				if($is_sel==false){
					$_SESSION['babili']['language'][$langue['country_code']]->isSelect=false;
				}
			}
		}
	}

	//Add ln_browser => firstime
	if(!isset($_SESSION['babili']['ln_browser'])){
		foreach($_SESSION['babili']['language'] as $key => $langue){
			if(strtoupper($key)==strtoupper($Langue_brw)){
				$_SESSION['babili']['language'][$key]->isSelect=true;
				$_SESSION['babili']['ln_browser']=$Langue_brw;
				$_SESSION['babili']['browser']=$langue;
			}
		}
	}


/*************************************************
//Get Reference and Target Langue
*************************************************/
	$i=0;
	foreach($resultLangues as $key => $langue){							
		if($i==0){
			$_SESSION['babili']['refLang']= new stdClass;
			$_SESSION['babili']['refLang']->language = $langue;//Default=US
			$_SESSION['babili']['refLang']->code = $key;//Default=US
			
			$_SESSION['babili']['refTag']= new stdClass;
			$_SESSION['babili']['refTag']->language = $langue;//Default=US
			$_SESSION['babili']['refTag']->code = $key;//Default=US
		}
		if(isset($_POST['lang']) && is_array($_POST['lang'])){
			$j=0;
			foreach($_POST['lang'] as $ln){
				if($j==1 && $key==$ln){
					$_SESSION['babili']['refTag']->language= $langue;
					$_SESSION['babili']['refTag']->code= $key;
					break;
				}
				$j++;
			}
		}
		$i++;
	}
	
	if($first==true && isset($_SESSION['babili']['ln_browser']) && $_SESSION['babili']['browser']->id_lang!=$_SESSION['babili']['refTag']->language['id']){
		$_SESSION['babili']['refTag']->code=$_SESSION['babili']['browser'];
	}



/*************************************************
//Get langues selected: for query
*************************************************/
	if($_SESSION['babili']['refLang']->id_lang != $_SESSION['babili']['refTag']->id_lang){
		$sel_lang=$_SESSION['babili']['refLang']->id_lang.",".$_SESSION['babili']['refTag']->id_lang;
		$tab_langues_view_status=array($_SESSION['babili']['refLang'],$_SESSION['babili']['refTag']); 
		$nbr_langues=2;	
	}else{
		$sel_lang=$_SESSION['babili']['refLang']->id_lang;
		$tab_langues_view_status=array($_SESSION['babili']['refLang']);
		$nbr_langues=1;	
	}
										
	foreach($_SESSION['babili']['language'] as $ln){
		if( $ln->isSelect==true && 
			$ln->id_lang != $_SESSION['babili']['refLang']->id_lang && 
			$ln->id_lang != $_SESSION['babili']['refTag']->id_lang 
		  )
		{ 
			$sel_lang.=",".$ln->language['id'];
			$tab_langues_view_status[]=$ln;
			$nbr_langues++;
		}
	}



/*************************************************
//Get Search Word
*************************************************/
	$searchWord='';
	if(isset($_POST['search_key']) && $_POST['search_key']!=''){
		$searchWord=$_POST['search_key'];
	}
	

	
/*************************************************
//Get Search By Date //Only for staff
*************************************************/
	$searchBeginDate='';
	if(isset($_POST['begindate']) && $_POST['begindate']!=''){
		$searchBeginDate=$_POST['begindate'];
	}
		
	$searchEndDate='';
	if(isset($_POST['enddate']) && $_POST['enddate']!=''){
		$searchEndDate=$_POST['enddate'];
	}



/*************************************************
//Get Selected Show 
*************************************************/	
	if($first==true && $_SESSION['babili']['gid']==0){
		$_SESSION['babili']['selectShow']="empty";
	}elseif($first==true && $_SESSION['babili']['gid']>1 ){
		$_SESSION['babili']['selectShow']="translated"; 
	}elseif($first==true){
		$_SESSION['babili']['selectShow']="all";
	}
	
	$is_first=$_SESSION['babili']['selectShow'];
	if($_SERVER['REQUEST_METHOD'] && isset($_POST['selectShow'])){
		$_SESSION['babili']['selectShow']=$_POST['selectShow'];
	}
		
	if($_SESSION['babili']['selectShow']=="by_author" && isset($_POST['translated_by_user']) && $_POST['translated_by_user']!=-1 ){
		$status_show="100";
	}elseif(isset($_POST['selected_file']) && $_SESSION['babili']['selectShow']=="order_by_files" && $_POST['selected_file']!=-1 ){
		$status_show="101";
	}else{
		if($_SESSION['babili']['selectShow']=="empty"){
			$status_show="0";
		}elseif($_SESSION['babili']['selectShow']=="translated" || $_SESSION['babili']['selectShow']=="order_by_date_desc"){
			$status_show="1";
		}elseif($_SESSION['babili']['selectShow']=="validated"){
			$status_show="2";
		}elseif($_SESSION['babili']['selectShow']=="my_translated_label"){
			$status_show="99";
		}else{
			$status_show="0,1,2";
		}
		
		$_POST['translated_by_user']=array();
		$_POST['selected_file']=array();
	}	
	



/*************************************************
//Get Select Item 
*************************************************/	
	if(!isset($_SESSION['item_select']) || $_SESSION['item_select']<0 ){ 
		$_SESSION['item_select']=1;
	}
	
	
	
/*************************************************
//Get Show Keys/page 
*************************************************/	
	if(!isset($_POST['textShow']) && !isset($_SESSION['babili']['textShow'])){
		$_SESSION['babili']['textShow']=15;
	}
	if(isset($_POST['textShow'])){
		$_SESSION['babili']['textShow']= $_POST['textShow'];
	}




/*************************************************
//Get Number page selected
*************************************************/	
	if($is_first!="order_by_date_desc" && $_POST['selectShow']=='order_by_date_desc'){
		$_SESSION['babili']['num_page']=1;
		$_POST['selectPage']=1;
	}

	if($_SESSION['babili']['num_page']==0){
		$_SESSION['babili']['num_page']=1;
	}
	if(!isset($_SESSION['babili']['num_page']) && !isset($_POST['selectPage']) ){
		$_SESSION['babili']['num_page']=1;
	}elseif(isset($_POST['selectPage'])){
		$_SESSION['babili']['num_page']=$_POST['selectPage'];
	}



/*************************************************
//Get current product
*************************************************/	
	if(isset($_POST['product'])){
		$_SESSION['babili']['product']=$_POST['product'];
	}elseif(!isset($_SESSION['babili']['product'])){
		$_SESSION['babili']['product']=$resultProjects[0]['id'];
	}


/*************************************************
//Get current project
*************************************************/	
	if(isset($_POST['project'])){
		$_SESSION['babili']['project']=$_POST['project'];
	}elseif(!isset($_SESSION['babili']['project'])){
		$_SESSION['babili']['project']=$resultProjects[$_SESSION['babili']['product']][0]['id'];
	}

/*************************************************
//Get Files
*************************************************/
 $query = "
	SELECT *	
	FROM `file`
	WHERE `project_id`=".$_SESSION['babili']['project']."
	ORDER BY `path` ASC
 ";
 
 $resultFiles = fetchArray($query);

/*************************************************
//Get Count Keys in database
*************************************************/	

  //When Show = ( ALL ) - keys ref for all languages
	if( !isset($_SESSION['babili']['keys'][$_SESSION['babili']['project']]) || empty($_SESSION['babili']['keys'][$_SESSION['babili']['project']]) ){
		/** Select Only distinct keys **/
		$selectKeysNotDuplicate = "
			SELECT k.`id` 
			FROM `property_key` k 
			LEFT JOIN `translation` as t ON k.`id`=t.`property_key_id`
			WHERE t.`language_id` = 1 AND
				  k.`id` = ".intval($_SESSION['babili']['project'])."
		";
		
		$resultKeysNotDuplicate = fetchArray($selectKeysNotDuplicate);

		//serialize array['id_key']
		$KeysNotDuplicate=mySerialize($resultKeysNotDuplicate,'id_key');
		
		$_SESSION['babili']['keys'][$_SESSION['babili']['project']]= $KeysNotDuplicate;
	}
	
	$KeysNotDuplicate= $_SESSION['babili']['keys'][$_SESSION['babili']['project']];
	
  //End When Show = ( ALL ) - keys ref for all languages
  
  	
	$selectKeysNotDuplicate = "
		SELECT  k.`id` 
		FROM `translation` t
		LEFT JOIN `property_key` as k ON k.`id`=t.`property_key_id` ";
			
	if($searchWord!=''){
		$selectKeysNotDuplicate .= "
			JOIN `user` as u ON t.`contributor_id`=u.`id` ";
	}	
				
	$selectKeysNotDuplicate .= "
			WHERE k.`id` = ".intval($_SESSION['babili']['project'])." AND ";
	
	$selectKeysNotDuplicateWithouLang=$selectKeysNotDuplicate ;
	
	$selectKeysNotDuplicate.="			
			  t.`language_id`=".$_SESSION['babili']['refTag']->language['id']." AND ";




#####################
# Search
#####################	
	$exec=false;	
	
	//Search By keyword	
	$querySearch="";
	if($searchWord!=''){
		$exec=true;	
		
		switch($_POST['search_option']){
			case "exactly":
				$lf_str="";
				$rt_str="";
				break;
			case "begin":
				$lf_str="";
				$rt_str="%";
				break;			
			case "end":
				$lf_str="%";
				$rt_str="";
				break;				
			default:
				$lf_str="%";
				$rt_str="%";			
		}			
		
		if($_POST['search_option']=="bykey"){		  
			$querySearch="		
				
				 ( 					
					k.`name` LIKE '".$lf_str.addslashes($searchWord).$rt_str."' OR k.`id`='".addslashes($searchWord)."'
				) 
			 
			";
		}else{
			$querySearch="		
				
				 (
					t.`value` LIKE '".$lf_str.addslashes($searchWord).$rt_str."' OR 
					u.`email` LIKE '".$lf_str.addslashes($searchWord).$rt_str."' OR 
					k.`name` LIKE '".$lf_str.addslashes($searchWord).$rt_str."' 
				) 
			 
			";
		}
		
		$selectKeysNotDuplicate=str_replace('t.`language_id`='.$_SESSION['babili']['refTag']->language['id'],"t.`language_id` IN (".$sel_lang.")",$selectKeysNotDuplicate);
	}
	
	//Search By date
	$querySearchByDate="";
	if($searchBeginDate!='' || $searchEndDate!=''){
		$exec=true;
		
		if(strtotime($searchBeginDate)>strtotime($searchEndDate)){
			$perm=$searchBeginDate;
			$searchBeginDate=$searchEndDate;
			$searchEndDate=$perm;
		}
							  
		if($searchBeginDate!=''){
			$querySearchByDate.="
				  t.`date_modified` >= '".$searchBeginDate."' AND ";
		}
		
		if($searchEndDate!=''){
			$querySearchByDate.="
				  t.`date_modified` <= '".$searchEndDate."' AND ";
		}
		
		if(substr($querySearchByDate, -4)=="AND "){
			$querySearchByDate=substr($querySearchByDate,0,-4);
		}
		
		$selectKeysNotDuplicate=str_replace('t.`language_id`='.$_SESSION['babili']['refTag']->language['id'],"t.`language_id` IN (".$sel_lang.")",$selectKeysNotDuplicate);
	}
		
		
	if($exec==true){	
		if($querySearch!='' && $querySearchByDate!=''){
			$querySearch.= ' AND '.$querySearchByDate;
		}elseif($querySearchByDate!=''){
			$querySearch= $querySearchByDate;
		}
		if($querySearch!=''){
			$querySearch=" AND ".$querySearch;
		}
	}
	
	
	
/**
 * When Show = ( Translated | Validated | Empty | Translated by me )
**/		
		
####################
# Select By Me 
####################
	if($status_show=="99" || $_POST['translaed_opt']=='by_me'){
		$selectKeysNotDuplicate .=" 
			  t.`status`=1 AND t.`contributor_id`='".$_SESSION['babili']['id_user']->id_user."' ";
		if($_POST['translaed_opt']=='by_me')$selectKeysNotDuplicate .=" AND ";
	}
	
####################
# Select By User
####################
	if($status_show=="100"){	
		$selectKeysNotDuplicate .=" 
			  t.`contributor_id`='".$_POST['translated_by_user']."' ";
		$selectKeysNotDuplicateWithouLang.=" 
			  t.`contributor_id`='".$_POST['translated_by_user']."' ";
			  
	}
	
####################
# Select By File
####################
	if( $status_show=="101"){	
		$selectKeysNotDuplicate.="
			   k.`file_id`='".$_POST['selected_file']."' ";	
	} 
	 
	 
####################
# Add Filter Status
####################
	if(in_array($_POST['selectShow'],array('all','empty','translated','validated'))){
		$selectKeysNotDuplicate.=" 
			  t.`status` IN (".$status_show.") AND ";
	}
	

####################
# Add Filter Search
####################
	if(substr(trim(str_replace('\r','',trim($selectKeysNotDuplicate))), -3)=="AND"){
		$selectKeysNotDuplicate=trim(str_replace('\r','',trim($selectKeysNotDuplicate)));
		$selectKeysNotDuplicate =substr($selectKeysNotDuplicate,0,-3);
		$selectKeysNotDuplicate.=" 
			$querySearch
			";
	}else{
		$selectKeysNotDuplicate.=" 
			$querySearch
			";
	}
	
	//echo "<pre>".$selectKeysNotDuplicate."</pre>";

####################
# Grouper les translations vides si la langue != EN => Appliquer propagation
####################		
	if($status_show=="0" && $_SESSION['babili']['refTag']->language['id']!="1"){
		
		$arr_k = fetchArray($selectKeysNotDuplicate);
		
		if(count($arr_k)>0){
			foreach($arr_k as $it){
				$arr_i[]= $it['id_key'];				
			}
			$arr_i=implode(',',$arr_i);
			$selectKeysNotDuplicate="
				SELECT k.`id` 
				FROM `translation` t
				LEFT JOIN `property_key` as k ON  k.`id` =  t.`property_key_id`
				LEFT JOIN `file` as f ON  f.`id` =  k.`file_id`
				WHERE t.`language_id` = 1 AND
					  f.`project_id` = ".intval($_SESSION['babili']['project'])." AND
					  k.`id` IN (".$arr_i.") 
					  GROUP BY t.`value` ";
		}
	}
		
#####################
# Order By Date
#####################
	if($_POST['selectShow']=="order_by_date_desc"){
		$selectKeysNotDuplicate=trim($selectKeysNotDuplicate);
		if(substr(trim(str_replace('\r','',trim($selectKeysNotDuplicate))), -3)=="AND"){
			$selectKeysNotDuplicate=trim(str_replace('\r','',trim($selectKeysNotDuplicate)));
			$selectKeysNotDuplicate =substr($selectKeysNotDuplicate,0,-3);
		}
		$selectKeysNotDuplicate.='
			ORDER BY t.`date_modified` DESC	';
	}

	
######################
# Execute Query with filter
#####################	
	//echo "<pre>$selectKeysNotDuplicate</pre>";

	$resultKeysNotDuplicate = fetchArray($selectKeysNotDuplicate);

	$KeysNotDuplicate='';

	if(!empty($resultKeysNotDuplicate)){
		$KeysNotDuplicate=mySerialize($resultKeysNotDuplicate,'id');			
	}
	$resultCount=substr_count($KeysNotDuplicate,",");
	if($resultCount==0 && $KeysNotDuplicate!=""){
		$resultCount=1;
	}	
	 	   
	//By Status/Search OR ALL
	if(empty($KeysNotDuplicate) || $KeysNotDuplicate==""){	
		$wheres_all.=" AND k .`id` IN (0) ";
	}else{
		$wheres_all.=" AND t.`id` IN (".$KeysNotDuplicate.") ";
	}
 
 	//Get Ids US	
	$selectTransFinaleKeyIds="
		SELECT k.`id` 
		FROM `property_key` k 
		JOIN `translation` as t ON t.`property_key_id` = k .`id`
		JOIN `file` as f ON t.`id` = k .`file_id`	
		WHERE f.`project_id`='".intval($_SESSION['babili']['project'])."' 	
		AND t.`language_id`=1
		$wheres_all	
		ORDER BY k.`name`			
		";

 
/*************************************************
//Get Number total pages 
*************************************************/
	$nbrPages= ceil($resultCount / $_SESSION['babili']['textShow']);	
	if($_SESSION['babili']['num_page']>$nbrPages){
		$_SESSION['babili']['num_page']=$nbrPages;
		$_SESSION['item_select']=($nbrPages-1)*$_SESSION['babili']['textShow']+1;
	}
	
	if($is_first!="order_by_date_desc" && $_POST['selectShow']=='order_by_date_desc'){
		$_SESSION['item_select']=1;
	}
	
/*************************************************
//Get Num pages selected after next/prev click 
*************************************************/		
	if(isset($_POST['first_x'])) $_SESSION['babili']['num_page']=1;
	if(isset($_POST['last_x'])) $_SESSION['babili']['num_page']=$nbrPages;
	if(isset($_POST['next_x']) && $_SESSION['babili']['num_page']<=$nbrPages)$_SESSION['babili']['num_page']=$_SESSION['babili']['num_page']+1;
	if(isset($_POST['next_x']) && $_SESSION['babili']['num_page']> $nbrPages) $_SESSION['babili']['num_page']=1;
	if(isset($_POST['prev_x']) && $_SESSION['babili']['num_page']>1) $_SESSION['babili']['num_page']=$_SESSION['babili']['num_page']-1;
	
	if($_SESSION['item_select']>($_SESSION['babili']['num_page'])*$_SESSION['babili']['textShow']){		
		$_SESSION['item_select']=($_SESSION['babili']['num_page']-1)*$_SESSION['babili']['textShow']+1;
	}elseif($_SESSION['item_select']<=($_SESSION['babili']['num_page']-1)*$_SESSION['babili']['textShow']){
		$_SESSION['item_select']=($_SESSION['babili']['num_page']-1)*$_SESSION['babili']['textShow']+1;
	}	
	
	if($_SESSION['item_select']<0){
		$_SESSION['item_select']=1;
	}
	
/*************************************************
//Get Selected item and Num page after : Go->Key->num click 
*************************************************/	
	if(isset($_POST['goKey']) || isset($_POST['goKeyNum'])){					
		if( $_POST['goKeyNum'] > 0 && $_POST['goKeyNum']<=$resultCount ) {
			$_SESSION['babili']['num_page']= ceil( $_POST['goKeyNum'] / $_SESSION['babili']['textShow'] );
			$_SESSION['item_select']= $_POST['goKeyNum'];
		}
	}
	
/*************************************************
//Get langues selected: for query
*************************************************/	
	$offset=($_SESSION['babili']['num_page']*$_SESSION['babili']['textShow'])-($_SESSION['babili']['textShow']);
	if($offset<0){
		$offset=0;
	}
	
	$selectTransFinaleKeyIds.="
			LIMIT ".$_SESSION['babili']['textShow']."			
			OFFSET ".$offset;

	//Table qui contient tous les ids keys US	
	$resultTransFinale = fetchArray($selectTransFinaleKeyIds);
	
	$arrDataUs=array();
	//Get Us Translation
	if(count($resultTransFinale)>0){
		foreach($resultTransFinale as $it){
			$arrDataUs[]=$it['id_key'];
		}
	}

	if(count($arrDataUs)>0){
		//Final Query
		$selectTransFinaleNew ="
			SELECT k.`name`, k.`id`, k.`max_length`,
				   
				   t.`id` , t.`value`, t.`status`, t.`contributor_id`,
				   
				   CONCAT('trunk','\\\',f.`path`,'\\\','</b>{desc}') as name, 
				   
				   u.`email`, e.`email` as email_editor,
				   
				   t.`date_modified` as date_trans
			
			FROM `property_key` k 
			JOIN `file` as f ON f.`id`=k.`file_id`
			JOIN `translation` as t ON t.`property_key_id` = k .`id`
			LEFT JOIN `user` as u ON u.`id` = t.`contributor_id`
			LEFT JOIN `user` as e ON e.`id` = t.`validator_id`
			WHERE k.`id` IN (".implode(",",$arrDataUs).") 
			";
		
		$arrData=array();
		foreach($tab_langues_view_status as $item){
			//Language by language
			$resultTransFinale = fetchArray($selectTransFinaleNew." AND t.`language_id`=".$item->language['id']);
				
			foreach($resultTransFinale as $it){
				$arrData[$item->language['id']][]=$it;
			}
		}
		$arrDataFinale=array();
		foreach($arrDataUs as $it){
			foreach($tab_langues_view_status as $ln){
				foreach($arrData[$ln->language['id']] as $item){
					if($item['id_key']==$it){
						$arrDataFinale[]=$item;
						break;
					}
				}
			}
		}	
	
		$resultTransFinale=$arrDataFinale;
		$TableAllWordsWithDetails= array();
		$id_tab_words=($_SESSION['babili']['num_page']-1)*$_SESSION['babili']['textShow']+1;
		$change_id="";
	
		foreach($resultTransFinale as $itm){
			if( $change_id!=$itm['id_key'] ){
				$change_id=$itm['id_key'];
				$TableAllWordsWithDetails[$itm['id_key']][0]=array($itm['key_name'],$itm['max_length'],addslashes($itm['name']),$id_tab_words);			
				$id_tab_words++;
			}
			//$itm->translation=str_replace("\r\n","\\n",$itm->translation);
			$TableAllWordsWithDetails[$itm['id_key']][$itm['id_lang']]=array(addslashes($itm['translation']),$itm['status'],$itm['id_lang'],$itm['contributor_id'],$itm['email'],$itm['email_editor']);		
		}

	//No results	
	}else{
		$TableAllWordsWithDetails=array();		
	}

	//Make table for javascript
	echo "<script type=\"text/javascript\">";
	echo php2js($TableAllWordsWithDetails,'arr');
	echo "</script>";
	
/*************************************************
//Get Ligne Selected 
*************************************************/
foreach($TableAllWordsWithDetails as $itm){
	if($_SESSION['item_select']==$itm[0][3] ){
		$line_selected=$itm;
		break;
	}
}

if(!(count($line_selected)>0) && count($TableAllWordsWithDetails)>0 ){	
	foreach($TableAllWordsWithDetails as $item){
		$_SESSION['item_select']= $item[0][3];
		$line_selected=$item;
		break;
	}
}

/*************************************************
//Get src logo status word
*************************************************/	
function getSrcLogoStatus($id_status){
	if($id_status==2){
		return  'img/accept.png';
	}elseif($id_status==1){
		return 'img/pencil.png';
	}elseif($id_status==0){
		return 'img/white.png';
	}else{
		return 'img/white.png';
	}
}	

/*************************************************
//Get src logo flag for langue
*************************************************/	
function getSrcFlag($id_lang){
	foreach($_SESSION['babili']['language'] as $ln){
		if($ln->language['id']== $id_lang){
			return $ln->language['flag'];
		}
	}
}

/*************************************************
//Get flag by status word
*************************************************/		
function getFlagStatus($id_status,$lang="",$type="",$index){
	return '<td><img id="img_status_tab_'.$index.'_'.$lang.'" src="'.getSrcLogoStatus($id_status).'" width="16" height="16" /></td>';
}	


//Get Header Module
function getHeaderMod($idMod=""){
	echo '<td class="box_module" valign="top" height="100%" '.$idMod.'>			
		   <table class="box_module_body" height="100%" cellpadding="0" cellspacing="0" width="100%">			
			 <tr> 			
			   <td valign="top">';
}

//Get Footer Module
function getFooterMod(){
	    echo '</td>
			</tr>
		  </table>		  
		</td>';
}

function getHeaderMod2($idMod=""){
	echo '<div class="box_module" height="100%" '.$idMod.'>			
		   <table class="box_module_body" height="100%" cellpadding="0" cellspacing="0" width="100%">			
			 <tr> 			
			   <td valign="top">';
}

//Get Footer Module
function getFooterMod2(){
	    echo '</td>
			</tr>
		  </table>		  
		</div>';
}
if($first==true)$first=false;

echo $classesFlags;
?>